package com.yildiz.ara.geomedikal;

import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.yildiz.ara.geomedikal.MyLocation.LocationResult;

public class Harita1 extends MapActivity {

	private MapView mapView;
	List<Overlay> mapOverlays;
	MyItemizedOverlay itemizedOverlay;
	Drawable drawable;
	public static Location loca;
	private MapController mc;
	private static Context context;
	public boolean isDie = false;
	private MyLocation myLocation;
	private double userLatitude, userLongtitude;
	private AsyncTask<Void, Void, Boolean> asyncTask;
	public static boolean killRunnable = false;

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	LocationResult locationResult = new LocationResult() {
		@Override
		public void gotLocation(Location location) {
			// TODO Auto-generated method stub
			// Log.i("MAP", "LocationResult.gotLocation()");
			if (!isDie);
				// Log.i("MAP",
				// "LocationResult.gotLocation() before nearestStationByLocation");
//				nearestStationByLocation(location); // Asynctask e giriyore.
			// Log.i("MAP",
			// "LocationResult.gotLocation() after nearestStationByLocation");
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.harita1);

		mapView = (MapView) findViewById(R.id.mapview);
		mc = mapView.getController();
		mc.setZoom(17);
		// Log.i("MAP", "after mc.setzoom()");
		context = getApplicationContext();
		userLatitude = 41.051994;
		userLongtitude = 29.009605;
		GoToNearestStation();
	}

	public static void toastShow() {

		Toast.makeText(context, R.string.noLocation, Toast.LENGTH_LONG).show();

	}

	private void showGPSDisabledAlertToUser() {
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
		alertDialogBuilder
				.setMessage("" + getText(R.string.gpsWarning))
				.setCancelable(false)
				.setPositiveButton("" + getText(R.string.yes),
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								Intent callGPSSettingIntent = new Intent(
										android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
								startActivity(callGPSSettingIntent);
							}
						});
		alertDialogBuilder.setNegativeButton("" + getText(R.string.no),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alert = alertDialogBuilder.create();
		alert.show();
	}

	// private void findMyLocation(final Location location){
	//
	// userLatitude = location.getLatitude();
	// userLongtitude = location.getLongitude();
	// GoToNearestStation();
	//
	// }
	public void nearestStationByLocation(final Location location) {
		asyncTask = new AsyncTask<Void, Void, Boolean>() {

			ProgressDialog dialog;

			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub

				killRunnable = true;
				dialog = ProgressDialog.show(Harita1.this, "", ""
						+ getText(R.string.progressDialog), true, false);
				userLatitude = location.getLatitude();
				userLongtitude = location.getLongitude();
				Log.e("MAP", "userLatitude: " + userLatitude);
				Log.e("MAP", "userLongtitude: " + userLongtitude);
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				// TODO Auto-generated method stub

				try {
//					userLatitude = location.getLatitude();
//					userLongtitude = location.getLongitude();
					userLatitude = 41.051994;
					userLongtitude = 29.009605;
				} catch (Exception e) {
					// TODO: handle exception
					return false;
				}

				Log.e("MAP", "userLatitude: " + userLatitude);
				Log.e("MAP", "userLongtitude: " + userLongtitude);
				return true;

			}

			@Override
			protected void onPostExecute(Boolean result) {
				// TODO Auto-generated method stub

				dialog.dismiss();
				if (result) {
					// Log.i("MAP", "before GoToNearestLocation");
					GoToNearestStation();
					// Log.i("MAP", "after GoToNearestLocation");

				} else
					Log.e("COHOUS", "Lokasyonlardan false geldi");

			}
		}.execute();
	}

	protected void GoToNearestStation() {

		// Log.i("MAP", "GoToNearestLocation-mid");
		// first overlay
		mapOverlays = mapView.getOverlays();
		drawable = getResources().getDrawable(R.drawable.currentlocation);
		itemizedOverlay = new MyItemizedOverlay(drawable, mapView);
		GeoPoint point = new GeoPoint((int) (userLatitude * 1E6),
				(int) (userLongtitude * 1E6));
		OverlayItem overlayItem = new OverlayItem(point, ""
				+ getText(R.string.mapUserLoc), "");
		itemizedOverlay.addOverlay(overlayItem);
		mapOverlays.add(itemizedOverlay);
		mc.animateTo(point);
		mapView.invalidate();
		// Log.i("MAP", "GoToNearestLocation-tail");
	}

	class MapOverlay extends com.google.android.maps.Overlay {
		private GeoPoint p;
		private Point screenPts;
		private Bitmap bmp;
		private long firstTime, lastTime;
		private int resId;

		public MapOverlay(GeoPoint geoPoint, int resId) {
			this.p = geoPoint;
			this.resId = resId;
		}

		@Override
		public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
				long when) {
			super.draw(canvas, mapView, shadow);
			// Log.d("COHOUS", "GoogleMapAct-> MapOverlay/draw");
			// ---translate the GeoPoint to screen pixels---
			screenPts = new Point();
			mapView.getProjection().toPixels(this.p, screenPts);

			// ---add the marker---
			bmp = BitmapFactory.decodeResource(getResources(), resId);
			canvas.drawBitmap(bmp, screenPts.x - (bmp.getWidth() / 2),
					screenPts.y - bmp.getHeight(), null);
			return true;
		}

		@Override
		public boolean onTouchEvent(MotionEvent e, MapView mapView) {
			// TODO Auto-generated method stub
			firstTime = System.currentTimeMillis();
			// Log.d("COHOUS", "GoogleMapAct-> MapOverlay/onTouchEvent");
			if (e.getX() < screenPts.x
					&& e.getX() > screenPts.x - bmp.getWidth()
					&& e.getY() < screenPts.y
					&& e.getY() > screenPts.y - bmp.getHeight()
					&& (firstTime - lastTime) > 500) {

			}
			lastTime = firstTime;
			return false;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		MyLocation.isNotDie = true;
		isDie = true;

	}

	@Override
	protected void onPause() {
		super.onPause();

	}

	@Override
	protected void onRestart() {
		super.onRestart();

	}

	@Override
	protected void onResume() {
		super.onResume();

		myLocation = new MyLocation();
		LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
		if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
				|| locationManager
						.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
			myLocation = new MyLocation();
			// Log.i("MAP", "before myLocation.init()");
			myLocation.init(getApplicationContext(), locationResult);
		} else {
			showGPSDisabledAlertToUser();
		}

	}

	@Override
	protected void onStart() {
		super.onStart();

	}

	@Override
	protected void onStop() {
		super.onStop();

	}

}
